package com.geese.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.geese.common.entity.OperationLog;
import com.geese.module.admin.service.OperationLogService;
import com.geese.module.user.model.SecurityUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.geese.common.constants.ResponseConstants;
import com.geese.common.util.JSONUtil;
import com.geese.common.vo.Page;
import com.geese.common.vo.PageVO;
import com.geese.exception.BusinessException;

/**
 * Created by Z先生 on 2017/2/23.
 */
public class BaseController {

    Logger log = Logger.getLogger(BaseController.class);

    @Autowired
    private OperationLogService operationLogService;

    protected HttpServletRequest request;
    protected HttpServletResponse response;

    /**
     * 该方法在执行controller之前执行，初始化request和response
     */
    @ModelAttribute
    public void setRequest(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
//        this.session=request.getSession();

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
    }


    public Integer[] StringToInt(String[] arrs) {
        Integer[] ints = new Integer[arrs.length];
        for (int i = 0; i < arrs.length; i++) {
            ints[i] = Integer.parseInt(arrs[i]);
        }
        return ints;
    }

    protected void printJson(String str)
    {
//        response.setContentType("text/json;charset=utf-8");
//        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        print(response, str);
    }

    protected void print(HttpServletResponse response, String str)
    {
        PrintWriter write = null;
        try {
            write = response.getWriter();
            write.print(str);
            write.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (write != null)
                write.close();
        }
    }
    
    
    protected Page getPageInfo(PageVO pageVO) {
    	return new Page(getCurrPage(pageVO.getCurrPage()), getPageSize(pageVO.getPageSize()));
    }
    
    protected Integer getCurrPage(String currPage){
        if(!StringUtils.isNumeric(currPage) || Objects.equals(currPage, "0")) {
            return  1;
        }
        return Integer.valueOf(currPage);
    }

	protected Integer getPageSize(String pageSize){
        if(!StringUtils.isNumeric(pageSize) || Objects.equals(pageSize, "0")) {
            return  10;
        }
        return Integer.valueOf(pageSize);
    }
    
    protected String response(Object data){
		Map<String,Object> response = new HashMap<String, Object>();
		response.put("code", ResponseConstants.SUCCESS);
		response.put("msg", "success");
		if(data != null ){
			response.put("result", data);
		}
		return JSONUtil.objectToJson(response);
	}
	
	protected String response(){
		return response(null);
	}
	
	protected List<String> checkIds(List<String> ids) {
		for(String id : ids) {
			if(!StringUtils.isNumeric(id)) {
				throw new BusinessException(130003);
			}
		}
		return ids;
	}

	protected void doLog(HttpServletRequest request, SecurityUser user, String context){
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        OperationLog operationLog = new OperationLog();
        operationLog.setContent(context);
        operationLog.setUserId(user.getUserId());
        operationLog.setIp(ip);
        operationLog.setUserName(user.getUserName());
        operationLogService.save(operationLog);
    }
}
